/**
 * @description  上交固收（债券指令）
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Modal } from 'antd';
import { PrimaryGhostC, PrimaryC, TableC } from '../../../../../comps';
import BasicInfoSj from './exchangeSj';
import { uniqueKey, AutomaticSettlement } from '../../../../../utils/commonFunc';
import style from '../index.less';
@Form.create()
class ExchangeStock extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  constructor() {
    super();
    this.state = {
      query: undefined, // 二次确认时回填信息
      isShow: false, // 控制二次确认model框展示
      currentUser: {}, // 当前登录用户信息
      querys: {}, // 发给后台的数据
      trailColumns: [], //试算结果列表
      trailDataSource: [], //试算结果数据
      trailModel: false, //试算模态框
      productCode: undefined, //产品code
      portfolioCode: undefined, //组合code
      uid: '',
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'interBankBasicInfoM/getUserInfo',
      payload: localStorage.getItem('antd-pro-userId'), // 获取对当前用户信息
      callback: (res) => {
        this.setState({
          currentUser: res,
        });
      },
    });
    const uid = uniqueKey();
    uid.then((r) => {
      this.setState({ uid: r });
    });
  }
  // 点击确定或下达
  handleOnClick = () => {
    const { type, isCanOrder } = this.props;
    const { currentUser, uid } = this.state;
    if (!isCanOrder && type == 1) {
      //在点击“下达”时，若标记指示未配置指令，则提示用户“该组合为配置指令，无法下发指令。
      message.warning(this.props.errorSetMsg);
      return;
    }
    const data = this.basicInfoSj.getInfo();
    if (data !== undefined) {
      const query = {
        // 用于二次确认回填的数据
        portfolioId: data.portfolioId,
        productId: data.productId,
        remark: data.remark, // 描述
        stockCode: data.info.exchangeCode,
        tradingMarket: securityExchange,
        uid: uid,
        trade2: {
          accruedInterest: data.accruedInterest, // 应计利息
          amount: data.amount, // 金额
          orderSide: data.orderSide, // 交易方向
          opponentTrading: data.opponentTrading, // 对手交易员
          externalName: data.externalName, // 交易对手
          orderQty: data.orderQty, // 数量
          fullPrice: data.fullPrice, // 全价
          settlementSpeed: data.settlementSpeed, // 清算速度
          direction: data.orderSide, // 交易方向
          price: data.price, // 净价
          settlementDate: data.settlementDate, // 日期
          yield: data.yield ? data.yield : null, // 买入收益率
          exerciseYield: data.exerciseYield ? data.exerciseYield : null, // 买入行权收益率
          securityExchange: data.securityExchange, // 交易市场
          engagedId: data.engagedId, // 约定号
          securityId: data.info.secucode + '-' + data.securityId,
          investmentType: data.investmentType,
          sppiResult: data.sppiResult,
          userDefinedType: data.userDefinedType,
          bussinessObjectives: data.bussinessObjectives,
          fee: data.fee,
        },
      };
      if (data.editObj) {
        query.trade2 = { ...query.trade2, ...data.editObj };
      }
      const querys = {
        // 下达指令或确定簿记的数据
        portfolioId: data.portfolioId,
        productId: data.productId,
        remark: data.remark, // 描述
        method: type == '1' ? null : '0', // 指令-null，簿记-0
        type: '2',
        userName: currentUser.name,
        userId: currentUser.userId,
        uid: uid,
        trade2: {
          securityId: data.info.secucode + '-' + data.securityId, // 证券代码
          securityExchange: data.securityExchange, // 交易市场
          orderSide: data.orderSide, // 交易方向
          engagedId: data.engagedId, // 约定号
          settlementSpeed: data.settlementSpeed, // 清算速度
          settlementDate: data.settlementDate, // 日期
          price: data.price, // 净价
          fullPrice: data.fullPrice, // 全价
          accruedInterest: data.accruedInterest, // 交易市场
          orderQty: data.orderQty, // 数量
          amount: data.amount, // 金额
          externalName: data.externalName, // 交易对手
          opponentTrading: data.opponentTrading, // 对手交易员
          yield: data.yield ? data.yield : null, // 买入收益率
          exerciseYield: data.exerciseYield ? data.exerciseYield : null, // 买入行权收益率
          investmentType: data.investmentType,
          sppiResult: data.sppiResult,
          userDefinedType: data.userDefinedType,
          bussinessObjectives: data.bussinessObjectives,
          fee: data.fee,
        },
      };
      if (data.editObj) {
        querys.trade2 = { ...querys.trade2, ...data.editObj };
      }
      if (type == '1') {
        this.setState(
          {
            query: query,
            querys: querys, // 指令下达时传给后台的数据
          },
          () => {
            this.setState({
              isShow: true,
            });
          },
        );
      } else if (type == '2') {
        this.setState(
          {
            querys: querys,
          },
          () => this.addData(),
        );
      } else if (type == '11') {
        this.setState(
          {
            querys: querys,
          },
          () => this.addData(),
        );
      }
    }
  };
  //试算按钮点击
  trialOnClick = () => {
    const { currentUser, productCode, portfolioCode } = this.state;
    const { type, dispatch } = this.props;
    const data = this.basicInfoSj.getInfo();
    if (data !== undefined) {
      const querys = {
        // 下达指令或确定簿记的数据
        portfolioId: data.portfolioId,
        productId: data.productId,
        remark: data.remark, // 描述
        method: type == '1' ? null : '0', // 指令-null，簿记-0
        type: '2',
        userName: currentUser.name,
        userId: currentUser.userId,
        businessType: '2',
        productCode: productCode, //产品code
        portfolioCode: portfolioCode, //组合code
        tenant: currentUser.tenant, //租户code
        trade2: {
          securityId: data.info.secucode + '-' + data.securityId, // 证券代码
          securityExchange: data.securityExchange, // 交易市场
          orderSide: data.orderSide, // 交易方向
          engagedId: data.engagedId, // 约定号
          settlementSpeed: data.settlementSpeed, // 清算速度
          settlementDate: data.settlementDate, // 日期
          price: data.price, // 净价
          fullPrice: data.fullPrice, // 全价
          accruedInterest: data.accruedInterest, // 交易市场
          orderQty: data.orderQty, // 数量
          amount: data.amount, // 金额
          externalName: data.externalName, // 交易对手
          opponentTrading: data.opponentTrading, // 对手交易员
          yield: data.yield ? data.yield : null, // 买入收益率
          exerciseYield: data.exerciseYield ? data.exerciseYield : null, // 买入行权收益率
          investmentType: data.investmentType,
          SPPI_result: data.SPPI_result,
          userDefinedType: data.userDefinedType,
          bussinessObjectives: data.bussinessObjectives,
        },
      };
      if (data.editObj) {
        querys.trade2 = { ...querys.trade2, ...data.editObj };
      }
      this.setState({ trailModel: true }, () => {
        dispatch({
          type: 'trailM/trialData',
          payload: querys,
          callback: (res) => {
            if (res) {
              this.setState({
                trailColumns: res.columns,
                trailDataSource: res.dataSource,
              });
            } else {
              this.setState({
                trailColumns: [],
                trailDataSource: [],
              });
            }
          },
        });
      });
    }
  };
  // 下方按钮
  showBtn = () => {
    const { type, loading } = this.props;
    if (type == '1' || type == '2' || type == '11') {
      let url = type == '1' ? 'bondTradeM/orderSave' : type == '2' ? 'bondTradeM/tradeBookSave' : 'portfolioTrialAddM/stockBondTradeSave';
      return (
        <div style={{ float: 'right', marginBottom: '10px' }}>
          {/* {type == "2" && <PrimaryC
            loading={loading.effects['trailM/trialData'] === true}
            onClick={() => this.trialOnClick()}
            title={'试算'}
            style={{ marginRight: "10px" }}
          />} */}
          <PrimaryC loading={loading.effects[url] === true} onClick={() => this.handleOnClick()} title={type == 1 ? '下达' : '确定'} />
          <PrimaryGhostC onClick={() => this.reset()} title='取消' style={{ marginLeft: '10px' }} />
        </div>
      );
    }
  };

  // 调用接口将数据传给后台
  addData = () => {
    const { money, position } = this.props;
    const { querys } = this.state;
    if (querys.trade2.orderSide == '1') {
      // 交易方向是买入时
      if (querys.trade2.settlementSpeed == '1') {
        // 结算速度T+0时
        if (querys.trade2.amount <= (money.t0 || 0)) {
          this.setData(querys);
        } else {
          message.warning('结算金额不能大于t+0可用');
        }
      } else if (querys.trade2.settlementSpeed == '2') {
        // 结算速度T+1时
        if (querys.trade2.amount <= (money.t1 || 0)) {
          this.setData(querys);
        } else {
          message.warning('结算金额不能大于t+0可用');
        }
      }
    } else if (querys.trade2.orderSide == '2') {
      // 交易方向是卖出时
      if (querys.trade2.orderQty <= (position.available || 0)) {
        this.setData(querys);
      } else {
        message.warning('数量不能大于可用数量');
      }
    } else if (querys.trade2.orderSide == '4') {
      // 交易方向是债回售时
      if (querys.trade2.orderQty <= (position.hold || 0)) {
        this.setData(querys);
      } else {
        message.warning('数量不能大于持仓数量');
      }
    }
  };

  // 下达指令或簿记确定
  setData = (querys) => {
    const { dispatch, type } = this.props;
    if (type == '1') {
      // 判断租户是否配置自动交收，若配置自动交收给予弹窗提醒
      if (
        AutomaticSettlement(type, 'bondTradeM/orderSave', querys, dispatch, (res) => {
          if (res && res.success == true) {
            message.success('指令下达成功');
            this.basicInfoSj.reset(); // 重置表单
            this.props.portfolioOnChange(undefined);
            this.props.tradingcodeOnChange(undefined);
            this.props.onOk(); // 调用父组件的ok方法
            this.setState({
              // 完成后将model框关闭
              isShow: false,
            });
          } else {
            message.error(res.errorMsg);
          }
          const uid = uniqueKey();
          uid.then((r) => {
            that.setState({ uid: r });
          });
        })
      )
        return;

      dispatch({
        type: 'bondTradeM/orderSave',
        payload: querys,
        callback: (res) => {
          if (res && res.success == true) {
            message.success('指令下达成功');
            this.basicInfoSj.reset(); // 重置表单
            this.props.portfolioOnChange(undefined);
            this.props.tradingcodeOnChange(undefined);
            this.props.onOk(); // 调用父组件的ok方法
            this.setState({
              // 完成后将model框关闭
              isShow: false,
            });
          } else {
            message.error(res.errorMsg);
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '2') {
      // 判断租户是否配置自动交收，若配置自动交收给予弹窗提醒
      if (
        AutomaticSettlement(type, 'bondTradeM/tradeBookSave', querys, dispatch, (res) => {
          if (res && res.success == true) {
            this.props.onOk();
            this.props.portfolioOnChange(undefined);
            this.props.tradingcodeOnChange(undefined);
            message.success('簿记下达成功');
            this.basicInfoSj.reset(); // 重置表单
          } else {
            message.error(res.errorMsg);
          }
          const uid = uniqueKey();
          uid.then((r) => {
            that.setState({ uid: r });
          });
        })
      )
        return;

      dispatch({
        type: 'bondTradeM/tradeBookSave',
        payload: querys,
        callback: (res) => {
          if (res && res.success == true) {
            this.props.onOk();
            this.props.portfolioOnChange(undefined);
            this.props.tradingcodeOnChange(undefined);
            message.success('簿记下达成功');
            this.basicInfoSj.reset(); // 重置表单
          } else {
            message.error(res.errorMsg);
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    } else if (type == '11') {
      dispatch({
        type: 'portfolioTrialAddM/stockBondTradeSave',
        payload: querys,
        callback: (res) => {
          if (res && res.success == true) {
            this.props.onOk();
            this.props.portfolioOnChange(undefined);
            this.props.tradingcodeOnChange(undefined);
            message.success('组合试算下达成功');
            this.basicInfoSj.reset(); // 重置表单
          } else {
            message.error(res.errorMsg);
          }
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        },
      });
    }
  };

  // 取消
  reset = () => {
    this.basicInfoSj.reset();
    this.props.portfolioOnChange(undefined);
    this.props.tradingcodeOnChange(undefined);
    if (this.props.type == '1' || this.props.type == '2' || this.props.type == '11') {
      this.props.onCancel();
    }
  };

  // 点击二次确认的确定按钮
  handleOk = () => {
    this.addData();
  };

  //点击二次确认的取消按钮
  handleCancel = () => {
    this.setState({
      isShow: false,
    });
  };

  // 二次确认model框
  showModel = () => {
    const { query, isShow } = this.state;
    const modalProps = {
      visible: isShow,
      title: '确认下达',
      width: 700,
      confirmLoading: this.props.loading.effects['bondTradeM/orderSave'] === true,
    };
    return (
      <div style={{ marginLeft: '200px' }}>
        <Modal {...modalProps} onOk={this.handleOk} onCancel={this.handleCancel}>
          <BasicInfoSj type={'3'} info={query} onRef={(ref) => (this.basicInfoSj1 = ref)} isSecondShow={true} />
        </Modal>
      </div>
    );
  };
  //试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };
  //试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <Modal
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </Modal>
    );
  };
  //获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e });
    } else this.setState({ portfolioCode: undefined });
  };
  //获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productCode: e });
    } else this.setState({ productCode: undefined });
  };
  render() {
    const { isShow, trailModel } = this.state;
    return (
      <div>
        <div>
          <BasicInfoSj
            businessType={this.props.businessType}
            portfolioOnChange={(e) => {
              this.props.portfolioOnChange(e);
            }}
            tradingcodeOnChange={(e) => {
              this.props.tradingcodeOnChange(e);
            }}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            type={this.props.type}
            info={this.props.info}
            onRef={(ref) => (this.basicInfoSj = ref)}
            investmentType={this.props.info ? undefined : this.props.position.investmentType}
          />
        </div>
        <div style={{ marginTop: '20px' }}>{this.showBtn()}</div>
        {isShow ? <div>{this.showModel()}</div> : null}
        {trailModel && this.showTrail()}
      </div>
    );
  }
}

export default connect(({ interBankBasicInfoM, bondTradeM, portfolioTrialAddM, loading, trailM, isAccountConfiguredM }) => ({
  interBankBasicInfoM,
  bondTradeM,
  portfolioTrialAddM,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
}))(ExchangeStock);
